package com.banciyuan.bcywebview.biz.picshow;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.view.dialog.DownLoadProgressDialog;
import com.banciyuan.bcywebview.base.view.dialog.WaitDialog;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.utils.download.DownLoadUtils;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.banciyuan.bcywebview.utils.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.IoUtils;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.DetailType;
import de.greenrobot.daoexample.model.OrignPic;

/**
 * Created by hy on 2015/6/29.
 */
public class ViewPictureActivity2 extends BaseActivity {

    private Map<Integer, Boolean> statusMap = new HashMap<>();
    private ViewPager pager;
    private String tempPath;
    private TextView tvPage;
    private DownLoadProgressDialog dialog;
    private WaitDialog waitDialog;
    private List<Fragment> mList = new ArrayList<>();
    private DetailType detailType;
    private String tagType;
    private List<String> imageUrls;
    private OrignPic orignPic;
    private TextView tv_save;
    private TextView tv_check;
    private TextView tv_load;
    private TextView tv_rotate;
    private LinearLayout btn_container;
    private int index;
    private int totalPage;

    private boolean orientation;
    private static final int REQUEST_WRITE_EXTERNAL_STORAGE = 2132;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newviewpicture);
        initArgs();
        initUi();
        initData();
    }

    @Override
    protected void onPause() {
        super.onPause();
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                ClearTmp(tempPath);
                return null;
            }
        }.execute();
    }

    @Override
    protected void initArgs() {
        Intent intent = getIntent();
        tempPath = ImageManager.getBigTempFile(this);
        imageUrls = intent.getStringArrayListExtra("imageUrls");
        index = intent.getIntExtra("position", 0);
        detailType = new DetailType();
        DetailDataHelper.getBaseDetailVaule(detailType, intent);
        switch (detailType.getTimelineType()) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
                tagType = "cos";
                break;
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                tagType = "illust";
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                tagType = "daily";
                break;
            case TimelineFactory.TIMELINE_TYPE_GROUP:
                tagType = "group_post";
                break;
            default:
                tagType = "";
                break;
        }
    }

    @Override
    protected void initAction() {
        tv_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ActivityCompat.checkSelfPermission(ViewPictureActivity2.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(ViewPictureActivity2.this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        MyToast.show(ViewPictureActivity2.this, getString(R.string.vailed_permission));
                    } else {
                        ActivityCompat.requestPermissions(ViewPictureActivity2.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                REQUEST_WRITE_EXTERNAL_STORAGE);
                    }
                } else {
                    save();
                }
            }
        });
        tv_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UserDataHelper.ifLogin(ViewPictureActivity2.this)) {
                    setBtnGone(View.GONE);
                    reloadHtml(index);
                } else {
                    MyToast.show(ViewPictureActivity2.this, getString(R.string.login_first));
                }
            }
        });
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                index = position;
                position = position + 1;
                tvPage.setText(position + "/" + totalPage);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        //判断请求码，确定当前申请的权限
        if (requestCode == REQUEST_WRITE_EXTERNAL_STORAGE) {
            //判断权限是否申请通过
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                save();
            } else {
                MyToast.show(ViewPictureActivity2.this, getString(R.string.operation_fail));
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void showDialog() {
        dialog = new DownLoadProgressDialog(this, R.style.Dialog);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.process(0);
    }

    private void showWaitDialog() {
        waitDialog = new WaitDialog(this, R.style.Dialog);
        waitDialog.setCanceledOnTouchOutside(false);
        waitDialog.show();
    }

    private void reloadHtml(int position) {
        if (orignPic.getMultis() != null && !orignPic.getMultis().isEmpty() && position < orignPic.getMultis().size()) {
            String remotePath = orignPic.getMultis().get(position).getPath();
            if (checkInDisk(remotePath)) {
                PicShowFragment fragment = (PicShowFragment) mList.get(position);
                fragment.parseImage(remotePath);
                statusMap.put(position, true);
            } else {
                showWaitDialog();
                showImage(remotePath, position);
            }
        }

    }

    private void save() {
        if (UserDataHelper.ifLogin(this)) {
            if (orignPic.isDownload()) {
                if (orignPic.getMultis() != null && !orignPic.getMultis().isEmpty() && index < orignPic.getMultis().size()) {
                    String remotePath = orignPic.getMultis().get(index).getPath();
                    if (checkInDisk(remotePath)) {
                        setTask(ImageLoader.getInstance().getDiskCache().get(remotePath), false);
                    } else {
                        showDialog();
                        loadImage(remotePath, true);
                    }
                }
            } else {
                MyToast.show(this, getString(R.string.cant_save));
            }
        } else {
            MyToast.show(this, getString(R.string.login_first));
        }
    }

    public void checkBtn(int position) {
        if (statusMap.get(position) == null) {
            String remotePath = orignPic.getMultis().get(position).getPath();
            if (checkInDisk(remotePath)) {
                PicShowFragment fragment = (PicShowFragment) mList.get(position);
                fragment.parseImage(remotePath);
                setBtnGone(View.GONE);
                statusMap.put(position, true);
            } else {
                setBtnGone(View.VISIBLE);
            }
        } else {
            setBtnGone(View.GONE);
        }
    }

    private void setBtnGone(final int status) {
        tv_check.post(new Runnable() {
            @Override
            public void run() {
                tv_check.setVisibility(status);
            }
        });
    }

    private void showImage(String url, final int index) {
        ImageLoader.getInstance().loadImage(url, null, ImageOptions.optionsCopy,
                new SimpleImageLoadingListener() {
                    @Override
                    public void onDiskCacheComplete(String imageUri, File mfile, String type) {
                        try {
                            if (!ViewPictureActivity2.this.isFinishing() && waitDialog.isShowing())
                                waitDialog.dismiss();
                            PicShowFragment fragment = (PicShowFragment) mList.get(index);
                            fragment.parseImage(imageUri);
                            statusMap.put(index, true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                },
                new ImageLoadingProgressListener() {
                    @Override
                    public void onProgressUpdate(String imageUri, View view, int current, int total) {
                    }
                }, true);
    }

    private void loadImage(String url, boolean decode) {
        ImageLoader.getInstance().loadImage(url, null, ImageOptions.optionsCopy,
                new SimpleImageLoadingListener() {
                    @Override
                    public void onDiskCacheComplete(String imageUri, File mfile, String type) {
                        dialog.process(99);
                        setTask(mfile, false);
                    }
                },
                new ImageLoadingProgressListener() {
                    @Override
                    public void onProgressUpdate(String imageUri, View view, int current, int total) {
                        float process = (float) current / total;
                        dialog.process((int) ((process * 99)));
                    }
                }, decode);
    }

    private void setTask(File file, final boolean decode) {
        new AsyncTask<File, Boolean, Boolean>() {
            @Override
            protected Boolean doInBackground(File... files) {
                boolean flag = false;
                try {
                    InputStream is = new FileInputStream(files[0]);
                    if (decode) {
                        flag = DownLoadUtils.saveReal(imageUrls.get(index), is, new IoUtils.CopyListener() {
                            @Override
                            public boolean onBytesCopied(int current, int total) {
                                return true;
                            }
                        });
                    } else {
                        flag = DownLoadUtils.save(imageUrls.get(index), is, new IoUtils.CopyListener() {
                            @Override
                            public boolean onBytesCopied(int current, int total) {
                                return true;
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return flag;
            }

            @Override
            protected void onPostExecute(Boolean aBoolean) {
                try {
                    if (!ViewPictureActivity2.this.isFinishing() && dialog.isShowing())
                        dialog.dismiss();
                    if (aBoolean) {
                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(DownLoadUtils.getFile(imageUrls.get(index)));
                        intent.setData(uri);
                        sendBroadcast(intent);
                        MyToast.show(ViewPictureActivity2.this, getString(R.string.pic_saved));
                    } else {
                        MyToast.show(ViewPictureActivity2.this, getString(R.string.download_fail));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.execute(file);
    }

    @Override
    protected void initData() {
        GetImageOriginHelper imageOriginHelper = new GetImageOriginHelper(this);
        imageOriginHelper.getImageOrigin(tagType, detailType, new GetOriginInter() {
            @Override
            public void succ(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                    Gson gson = new Gson();
                    orignPic = gson.fromJson(result, OrignPic.class);
                    renderData();
                } catch (Exception e) {
                    failLoad();
                }
            }

            @Override
            public void fail(String error) {
                failLoad();
            }
        });
    }

    private void failLoad() {
        tv_load.setText(getString(R.string.base_progressbar_failed));
        tv_load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initData();
            }
        });
    }

    private void renderData() {
        setAdapter();
        initAction();
        tv_load.setVisibility(View.GONE);
        btn_container.setVisibility(View.VISIBLE);
    }


    @Override
    protected void initUi() {
        dialog = new DownLoadProgressDialog(this);
        tv_save = (TextView) findViewById(R.id.tv_save);
        tv_check = (TextView) findViewById(R.id.tv_check);
        tv_load = (TextView) findViewById(R.id.tv_load);
        tv_rotate = (TextView) findViewById(R.id.tv_rotate);
        btn_container = (LinearLayout) findViewById(R.id.btn_container);
        pager = (ViewPager) findViewById(R.id.pager);
        tvPage = (TextView) findViewById(R.id.tv_page);

        tv_rotate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (orientation) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    orientation = false;
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    orientation = true;
                }
            }
        });
    }

    private void setAdapter() {
        for (int i = 0; i < imageUrls.size(); i++) {
            Fragment fragment = new PicShowFragment();
            Bundle bundle = new Bundle();
            if (i < orignPic.getMultis().size()) {
                if (checkInDisk(orignPic.getMultis().get(i).getPath())) {
                    imageUrls.set(i, orignPic.getMultis().get(i).getPath());
                    statusMap.put(i, true);
                    if (i == index) {
                        setBtnGone(View.GONE);
                    }
                }
            }
            bundle.putString("path", imageUrls.get(i));
            bundle.putInt("index", i);
            fragment.setArguments(bundle);
            mList.add(fragment);
        }
        pager.setAdapter(new MyAdapter(getSupportFragmentManager()));
        pager.setCurrentItem(index);
        totalPage = imageUrls.size();
        int newPosition = index + 1;
        tvPage.setText(newPosition + "/" + totalPage);
        tvPage.setVisibility(View.VISIBLE);
    }

    private void ClearTmp(String path) {
        try {
            File file = new File(path);
            if (file.isDirectory()) {
                File[] tmp = file.listFiles();
                for (int i = 0; i < tmp.length; i++) {
                    if (tmp[i].isFile()) {
                        tmp[i].delete();
                    } else if (tmp[i].isDirectory()) {
                        ClearTmp(tmp[i].getAbsolutePath());
                    } else {
                        continue;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Boolean checkInDisk(String url) {
        File file = ImageLoader.getInstance().getDiskCache().get(url);
        return file != null;
    }

    class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mList.get(position);
        }

        @Override
        public int getCount() {
            return mList.size();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }
}
